package com.run.runbbs.shiro;

import com.run.runbbs.entity.User;
import com.run.runbbs.service.impl.UserService;
import com.run.runbbs.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //授权
    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     * shiro默认开启授权缓存，不开启认证缓存，先从缓存中查找授权信息，没有再执行授权方法。
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userId=jwtUtils.getClaimByToken(principalCollection.toString()).getSubject();
        User user=userService.findUserById(Integer.valueOf(userId));
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        Set<String> permission = new HashSet<>(Arrays.asList("view,edit".split(",")));
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken=(JwtToken) authenticationToken;
        //解析jwt获取userId，在创建jwt时已经是把userId放在token里了。
        String userId=jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        User user=userService.findUserById(Integer.valueOf(userId));
        if(user==null){
            throw new UnknownAccountException("用户不存在");
        }
        if(user.getStatus()==-1){
            throw new LockedAccountException("账号已被锁定");
        }

        AccountProfile profile=new AccountProfile();
        BeanUtils.copyProperties(user,profile);
        //将info返回securityManager安全管理器进行login处理。
//        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
        return new SimpleAuthenticationInfo(jwtToken.getCredentials(),jwtToken.getCredentials(),getName());
    }
}
